package com.liuyucheng.concurrent.exchanger;

import java.util.concurrent.Exchanger;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ExchangerDemo {
    public static void main(String[] args) {
        // 创建 Exchanger 实例，指定交换数据类型为 String
        Exchanger<String> exchanger = new Exchanger<>();
        ExecutorService executor = Executors.newFixedThreadPool(2);

        // 线程 1：生成数据并交换
        executor.execute(() -> {
            try {
                String data1 = "线程1的数据";
                System.out.println("线程1准备交换数据：" + data1);
                // 等待交换，获取线程2的数据
                String receivedData = exchanger.exchange(data1);
                System.out.println("线程1交换成功，收到数据：" + receivedData);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // 线程 2：生成数据并交换
        executor.execute(() -> {
            try {
                String data2 = "线程2的数据";
                System.out.println("线程2准备交换数据：" + data2);
                // 等待交换，获取线程1的数据
                String receivedData = exchanger.exchange(data2);
                System.out.println("线程2交换成功，收到数据：" + receivedData);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        executor.shutdown();
    }
}